package org.freemarker.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {
	private String LOGIN_ACTION_URI;

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		LOGIN_ACTION_URI = fConfig.getInitParameter("loginActionURI");
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession();
		String username = (String) session.getAttribute("user");
		
		if (!req.getRequestURI().equals("/FreemarkerTutorial/")
				&& !req.getRequestURI().equals("/FreemarkerTutorial/home")
				&& !req.getRequestURI().equals("/FreemarkerTutorial/register")
				&& !req.getRequestURI().matches(".*[.].*")) {
			
			if (username == null
					&& !LOGIN_ACTION_URI.equals(req.getRequestURI())) {
				RequestDispatcher rd = req
						.getRequestDispatcher("views/login/login.ftl");
				rd.forward(request, response);
				return;
			}
		}
		chain.doFilter(request, response);
	}
}